import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
import { useNavigate } from 'react-router-dom'
import {
  edituser,
  edituserInfo,
  uploadPhotoAction,
} from '@/store/actions/profile'
import styles from './index.module.scss'

import { useinitstate } from '@/hooks'
import EditInpit from '../EditInput'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { AppDispatch } from '@/store'
import Eidtsex from '../Eidtsex'
import dayjs from 'dayjs'
import { delToken } from '@/store/modules/login'
const Item = List.Item
export type InputShow = {
  type: '' | 'name' | 'intro'
  value: string
  show: boolean
}
export type Show = {
  type: '' | 'gender' | 'photo'
  show: boolean
}
const ProfileEdit = () => {
  const nav = useNavigate()
  const dis = useDispatch<AppDispatch>()
  // const dis = useDispatch<AppDispatch>()
  // useEffect(() => {
  //   dis(edituser())
  // }, [])
  // const {
  //   editUser: { photo, name, intro, gender, birthday },
  // } = useSelector((state: RootState) => state.profile)
  const {
    editUser: { photo, name, intro, gender, birthday },
  } = useinitstate(edituser, 'profile')
  const [show, setShow] = useState<InputShow>({
    type: '', // 修改昵称值为：name | 修改简介值为：intro
    value: '', // 对应字段的值
    show: false, // 控制弹层显隐
  })
  const openPop = (type: '' | 'name' | 'intro', value: string) => {
    setShow({
      type: type,
      value: value,
      show: true,
    })
  }
  const colsePop = () => {
    setShow({
      type: '',
      value: '',
      show: false,
    })
  }
  const updateInfo = async (value: string | number, type: string) => {
    try {
      if (type === 'photo') {
        file.current?.click()
      } else {
        await dis(edituserInfo({ [type]: value }))
        Toast.show({
          content: '修改成功',
        })
        colsePop()
        closedir()
      }
    } catch (error) {}
  }
  const [showdir, setshowdir] = useState<Show>({
    type: '',
    show: false,
  })
  const opendir = (type: '' | 'gender' | 'photo') => {
    setshowdir({
      type: type,
      show: true,
    })
  }

  const closedir = () => {
    setshowdir({
      type: '',
      show: false,
    })
  }
  const file = useRef<HTMLInputElement>(null)
  const uploadPhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    /**
     * 上传头像：
     * 1. 获取拍照或选择图片的文件file对象
     * 2. 调用后台接口上传图片，得到图片存储地址
     * 3. 再调用更新用户头像接口
     */
    if (!e.target.files?.length) return
    // 准备头像上传需要的参数=》FormData
    const fm = new FormData()
    fm.append('photo', e.target.files[0])
    await dis(uploadPhotoAction(fm))
  }
  const [showDate, setShowDate] = useState(false)
  const openDate = () => {
    setShowDate(true)
  }
  const closeDate = () => {
    setShowDate(false)
  }
  const updateBirth = async (selDate: Date) => {
    await updateInfo(dayjs(selDate).format('YYYY-MM-DD'), 'birthday')
    closeDate()
  }

  const logout = () => {
    Dialog.confirm({
      title: '提示：确认退出极客园吗？',
      confirmText: '退出',
      onConfirm: () => {
        console.log('退出')
        dis(delToken({ token: '', refresh_token: '' }))
        nav('/login')
      },
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          onBack={() => nav('/my')}
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}>
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              onClick={() => opendir('photo')}
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      photo || 'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt=""
                  />
                </span>
              }
              arrow>
              头像
            </Item>
            <Item
              arrow
              extra={name || '黑马先锋'}
              onClick={() => openPop('name', name)}>
              昵称
            </Item>
            <Item
              onClick={() => openPop('intro', intro)}
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {intro || '未填写'}
                </span>
              }>
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              onClick={() => opendir('gender')}
              arrow
              extra={gender ? '女' : '男'}>
              性别
            </Item>
            <Item arrow extra={birthday || '--'} onClick={openDate}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={showDate}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            onCancel={closeDate}
            onConfirm={updateBirth}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={logout}>
            退出登录
          </Button>
        </div>
      </div>
      <Popup visible={show.show} position="left">
        <EditInpit
          type={show.type}
          value={show.value}
          colsePop={colsePop}
          update={updateInfo}></EditInpit>
      </Popup>
      <Popup visible={showdir.show} position="bottom">
        <Eidtsex
          type={showdir.type}
          onClose={closedir}
          update={updateInfo}></Eidtsex>
      </Popup>
      <input ref={file} type="file" onChange={uploadPhoto} hidden />
    </div>
  )
}

export default ProfileEdit
